package com.atyjh.reggie.exception;

import com.atyjh.reggie.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 *
 * @author yjh
 * @since jdk1.8.0_311 2022.06.15
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理添加员工时，员工账号相同的异常
     *
     * @param ex 异常
     * @return 返回给前端的错误信息
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {

        if (ex.getMessage().contains("Duplicate entry")) {
            String[] split = ex.getMessage().split(" ");
            return Result.error("账号" + split[2] + "已存在");
        }

        return Result.error("未知错误");
    }

    /**
     * 捕获自定义异常，分类的删除异常
     *
     * @param ex 异常
     * @return 返回给前端的错误信息
     */
    @ExceptionHandler(value = {CategoryException.class})
    public Result<String> exceptionHandler(CategoryException ex) {

        log.error(ex.getMessage());
        return Result.error(ex.getMessage());

    }

}


















